import { get_patient_list, get_platformuser_select } from '@/services/patient';
import calculate_age from '@/utils/age';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';
import PatientDetails from './components/PatientDetails';
import SetDoctors from './components/SetDoctors';
import ImportPatient from './components/ImportPatient';
import AuthorizedChronicDisease from './components/AuthorizedChronicDisease';
import { useModel } from '@umijs/max';
import AddCoordinate from './components/AddCoordinate';
type GithubIssueItem = {
  phone: string;
  id: number;
  name: string;
  sex: string;
  birth: string;
  id_card: string;
  address: number;
  create_time: string;
  bind_doctor: [{ id: number; username: string }];
  info_status: number;
  province: string;
  city: string;
  area: string;
  family_address: string;
};
const AllPatient = () => {
  const actionRef = useRef<ActionType>();
  // 存储当前id
  const [id, setId] = useState<number>();
  // 存储当前身份证号
  const [id_card, setId_card] = useState<any>();
  // 存储结对医生下拉框数据
  const [doctors, setDoctors] = useState<any>([]);
  // 控制设置结对医生模态框的状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 控制患者详情模态框的状态
  const [isModalOpen1, setIsModalOpen1] = useState(false);
  // 存储已设置的结对医生
  const [selectedDoctors, setSelectDoctors] = useState<any>([]);
  // 存储导入患者模态框状态
  const [importPatient, setImportPatient] = useState(false);
  // 存储授权慢病模态框的状态
  const [authorizedChronicDisease, setAuthorizedChronicDisease] = useState(false);
  // 存储添加坐标模态框的状态
  const [isAddCoordinateModalOpen,setIsAddCoordinateModalOpen]=useState(false);
  // 存储用户信息
  const { initialState, setInitialState } = useModel('@@initialState');

  // 控制设置结对医生模态框显示和隐藏
  const isShowModal = (show: boolean) => {
    setIsModalOpen(show);
  };
  // 控制患者详情模态框显示和隐藏
  const isShowModal1 = (show: boolean) => {
    setIsModalOpen1(show);
  };
  // 控制导入患者模态框的显示与隐藏
  const isShowImportPatientModal = (show: boolean) => {
    setImportPatient(show)
  }
  // 控制授权慢病模态框的显示与隐藏
  const isShowAuthorizedChronicDiseaseModal = (show: boolean) => {
    setAuthorizedChronicDisease(show)
  }
  // 控制添加坐标模态框的显示与隐藏
  const isShowAddCoordinateModal=(show:boolean)=>{
    setIsAddCoordinateModalOpen(show)
  }
  // 获取患者列表数据
  const getPatientData = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    //默认分页参数和后端接口字段不匹配
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
      type: 'all',
    };
    // console.log(params);
    const res = await get_patient_list(request_body);
    console.log('患者列表', res);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 获取结对医生下拉列表
  useEffect(() => {
    const getDoctorList = async () => {
      let res = await get_platformuser_select();
      let arr: any = [];
      res.data.map((item: { id: number; username: any }) => {
        arr[item.id] = { text: item.username };
      });
      setDoctors(arr);
      // console.log('结对医生', res, arr);
    };
    getDoctorList();
  }, []);

  // 患者列表字段
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      key: 'index',
      dataIndex: 'index',
      valueType: 'index',
      width: 48,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username',
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '未知',
        },
        1: {
          text: '男',
        },
        2: {
          text: '女',
        },
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      onFilter: true,
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        0: {
          text: '未知',
        },
        1: {
          text: '男',
        },
        2: {
          text: '女',
        },
      },
    },
    {
      title: '年龄',
      dataIndex: 'birth',
      key: 'birth',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return calculate_age(record.birth);
      },
    },
    {
      title: '身份证号',
      key: 'id_card',
      dataIndex: 'id_card',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '家庭住址',
      key: 'family_address',
      dataIndex: 'family_address',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return record.province ? (
          <Tooltip title={record.province + record.city + record.area + record.family_address}>
            {(record.province + record.city + record.area + record.family_address).length > 10
              ? (record.province + record.city + record.area + record.family_address).substring(
                0,
                10,
              ) + '...'
              : record.province + record.city + record.area + record.family_address}
          </Tooltip>
        ) : (
          record.family_address
        );
      },
    },
    {
      title: '加入时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '加入时间',
      dataIndex: 'create_time',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
    },
    {
      title: '结对医生',
      dataIndex: 'platformuser_id',
      key: 'platformuser_id',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => (
        <Tooltip title={record.bind_doctor.map((item) => item.username).join()}>
          {record.bind_doctor.map((item) => item.username).join().length > 5
            ? record.bind_doctor
              .map((item) => item.username)
              .join()
              .substring(0, 5) + '...'
            : record.bind_doctor.map((item) => item.username).join()}
        </Tooltip>
      ),
    },
    {
      title: '结对医生',
      dataIndex: 'platformuser_id',
      key: 'platformuser_id',
      align: 'center',
      hideInTable: true,
      valueType: 'select',
      valueEnum: doctors,
      fieldProps: {
        showSearch: true,
        filterOption: (input: any, option: any) =>
          (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
      },
    },
    {
      title: '状态',
      dataIndex: 'info_status',
      key: 'info_status',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        0: {
          text: '未完善信息',
        },
        1: {
          text: '已完善信息',
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      key: 'option',
      render: (text, record, _, action) => (
        <>
          <Button
            key="coordinate"
            type="link"
            onClick={() => {
              setId(record.id);
              isShowAddCoordinateModal(true);
            }}
          >
            添加坐标
          </Button>
          {record.info_status === 0 ? (
            <Tooltip title="该用户未完善信息，不能设置医生">
              <Button
                key="editable"
                type="link"
                onClick={() => {
                  setId(record.id);
                  let res: any = [];
                  record.bind_doctor.map((item) => res.push(item.id));
                  setSelectDoctors(res);
                  isShowModal(true);
                }}
                disabled
              >
                设置医生
              </Button>
            </Tooltip>
          ) : (
            <Button
              key="editable"
              type="link"
              onClick={() => {
                setId(record.id);
                let res: any = [];
                record.bind_doctor.map((item) => res.push(item.id));
                setSelectDoctors(res);
                isShowModal(true);
              }}
            >
              设置医生
            </Button>
          )}
          <Button
            key="view"
            type="link"
            onClick={() => {
              setId(record.id);
              setId_card(record.id_card != '' ? record.id_card : undefined);
              isShowModal1(true);
            }}
          >
            患者详情
          </Button>
        </>
      ),
    },
  ];
  return (
    <PageContainer
      header={{
        breadcrumb: {},
      }}
    >
      <ProTable<GithubIssueItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params = {}) => getPatientData(params)}
        editable={{
          type: 'multiple',
        }}
        rowKey={(record) => record.id}
        search={{
          labelWidth: 'auto',
          collapseRender: false,
          collapsed: false,
          span: 6,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="患者列表"
        toolBarRender={() => [
          <Button
            key="import"
            onClick={() => {
              isShowImportPatientModal(true);
            }}
            type="primary"
          >
            导入患者
          </Button>,
          initialState?.currentUser?.current_platform.model_permissions?.includes('chronic_diseases') ?
            <Button
              key="authorization"
              onClick={() => {
                isShowAuthorizedChronicDiseaseModal(true)
              }}
              type="primary"
            >
              授权慢病
            </Button> : <></>
        ]}
      />
      {/* 设置结对医生 */}
      {isModalOpen ? (
        <SetDoctors
          isModalOpen={isModalOpen}
          isShowModal={isShowModal}
          selectedDoctors={selectedDoctors}
          id={id}
          actionRef={actionRef}
        ></SetDoctors>
      ) : (
        ''
      )}
      {/* 查看患者详情 */}
      {isModalOpen1 ? (
        <PatientDetails
          isModalOpen1={isModalOpen1}
          isShowModal1={isShowModal1}
          id_card={id_card}
          id={id}
        ></PatientDetails>
      ) : (
        ''
      )}
      {/* 导入患者 */}
      {importPatient ? <ImportPatient actionRef={actionRef} importPatient={importPatient} isShowImportPatientModal={isShowImportPatientModal}></ImportPatient> : ''}
      {/* 授权慢病 */}
      {authorizedChronicDisease ? <AuthorizedChronicDisease authorizedChronicDisease={authorizedChronicDisease} isShowAuthorizedChronicDiseaseModal={isShowAuthorizedChronicDiseaseModal} actionRef={actionRef}></AuthorizedChronicDisease> : ""}
      {/* 添加坐标 */}
      {isAddCoordinateModalOpen?<AddCoordinate isShowAddCoordinateModal={isShowAddCoordinateModal} isAddCoordinateModalOpen={isAddCoordinateModalOpen} id={id} actionRef={actionRef}></AddCoordinate>:''}
    </PageContainer>
  );
};

export default AllPatient;
